const path = require("path");
const { HarParser, CommonHeaderAnalyzer, FieldRelationshipAnalyzer, ApiGroupAnalyzer, StepAnalyzer } = require("../harAnalysis");
const JmxGenerator = require("./JmxGenerator");

class JmxWorker {

    /**
     * 
     * @param {{host: string, port: number, db: number}} redis 
     */
    constructor(redis) {
        this.redis = redis;
    }

    /**
     * 执行工作流程，解析 HAR 文件，分析相关信息并生成 JMX 文件。
     * 
     * @param {string} harPath
     * @param {string} jmxPath
     * @param {{url: {includes: string}}[]} harFilterConfig
     * @param {string} testPlanName
     * @param {{redisKey: string, redisVariableNames: string[], jmxVariableNames: string[]}} inputConfigs
     * @param {{redisKey: string, redisVariableNames: string[], jmxVariableNames: string[]}} outputConfigs
     * @param {{headerNames: string[], authorization: string}} headerConfig
     * @param {{urlPath: string, name: string}[]} forcedRequestConfigs
     * @param {{urlPath: string, name: string}[]} forcedResponseConfigs
     * @param {{field1: {urlPath: string, name: string}, field2: {urlPath: string, name: string}}[]} mapRequestConfigs
     * @param {{field1: {urlPath: string, name: string}, field2: {urlPath: string, name: string}}[]} mapResponseConfigs
     * @param {{urlPath: string, name: string, value: string}[]} customRequestConfigs
     * @param {{urlPath: string, name: string}[]} ignoreRequestConfigs
     * @param {{urlPath: string, name: string}[]} ignoreResponseConfigs
     * @param {{stepName: string, urlPaths: []}[]} stepConfigs
     */
    work(harPath, jmxPath, harFilterConfigs, testPlanName, inputConfigs, outputConfigs, headerConfig, forcedRequestConfigs, forcedResponseConfigs, mapRequestConfigs, mapResponseConfigs, customRequestConfigs, ignoreRequestConfigs, ignoreResponseConfigs, stepConfigs) {


        const harFilePath = path.resolve(harPath, `${testPlanName}.har`);
        const harParser = new HarParser(harFilePath, harFilterConfigs);
        const apis = harParser.parse();

        const commonHeaderAnalyzer = new CommonHeaderAnalyzer(apis, headerConfig);
        const commonHeaders = commonHeaderAnalyzer.analyze();

        const fieldRelationshipAnalyzer = new FieldRelationshipAnalyzer(apis, forcedRequestConfigs, forcedResponseConfigs, mapRequestConfigs, mapResponseConfigs, ignoreRequestConfigs, ignoreResponseConfigs);
        const variables = fieldRelationshipAnalyzer.analyze();

        const apiGroupAnalyzer = new ApiGroupAnalyzer(apis, variables);
        let groups = apiGroupAnalyzer.analyze();

        const stepAnalyzer = new StepAnalyzer(stepConfigs);
        groups = stepAnalyzer.analyze(groups);

        const jmxGenerator = new JmxGenerator(this.redis, jmxPath, testPlanName, commonHeaders, groups, variables, inputConfigs, outputConfigs, customRequestConfigs);

        jmxGenerator.setGuiMode(false);
        jmxGenerator.generateJmx();
        jmxGenerator.save();

    }

}

module.exports = JmxWorker;